<template>
  <div class="detail-container">
    <el-form
      ref="postForm"
      :model="postForm"
      :rules="rules"
      label-width="150px"
      label-suffix=":"
    >

      <sticky :z-index="10" :class-name="'sub-navbar ' + postForm.color">
        <el-button v-loading="loading" type="success" @click="submitForm">
          {{ isEdit ? '更新' : '保存' }}
        </el-button>
      </sticky>

      <div class="app-container" style="padding: 10px 20px">
        <warn />

        <el-row>
          <el-col :span="22">
            <el-form-item label="用户名" prop="username" required>
              <el-input v-model.trim="postForm.username" :disabled="isEdit" />
              <span>建议填写手机号码</span>
            </el-form-item>
            <el-form-item label="是否为线下店" prop="is_shop" required v-if="false">
              <el-select
                v-model="postForm.is_shop"
                clearable
                class="filter-item"
                placeholder="请选择"
              >
                <el-option
                  v-for="item in shopList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
              <span style="margin-left: 10px">区分供应商与线下店</span>
            </el-form-item>
            <el-form-item label="所属地区" v-if="false">
              <el-select
                v-model="postForm.address_id"
                clearable
                class="filter-item"
                placeholder="请选择地区"
              >
                <el-option
                  v-for="item in addressList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
              <span style="margin-left: 10px">线下店地区</span>
            </el-form-item>
            <el-form-item label="所属分类" v-if="false">
              <el-select
                v-model="postForm.category_id"
                clearable
                class="filter-item"
                placeholder="请选择分类"
              >
                <el-option
                  v-for="item in categoryList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
              <span style="margin-left: 10px">线下店使用,产品供应商可以不使用</span>
            </el-form-item>
            <el-form-item label="商家名称" prop="name" required>
              <el-input v-model.trim="postForm.name" />
              <span>建议不超过10个字</span>
            </el-form-item>
            <el-form-item label="联系电话" prop="mobile" required>
              <el-input v-model.trim="postForm.mobile" />
            </el-form-item>
            <el-form-item label="联系人" prop="nickname" required>
              <el-input v-model.trim="postForm.nickname" />
            </el-form-item>
            <el-form-item label="联系地址" prop="address" required>
              <el-input v-model.trim="postForm.address" />
            </el-form-item>
            <el-form-item label="商家让利" prop="discount" required>
              <el-input v-model.number="postForm.discount" />
              <span>百分比, %</span>
            </el-form-item>
            <el-form-item prop="image" label="营业执照">
              <upload-image
                bucket="supplier"
                :max="10"
                :width="750"
                :height="750"
                :quality="50"
                :file-list="postForm.image"
                is-default
                @onSuccess="onSuccess"
                @onRemove="onRemove"
              />
              <span>请上传相关证件, 最多可以上传10张</span>
            </el-form-item>
            <el-form-item label="排序" prop="sort" style="width: 200px">
              <el-input v-model.number="postForm.sort" />
              <span>-128 ~ 127</span>
            </el-form-item>
            <el-form-item label="状态" style="width: 200px">
              <el-switch v-model="postForm.status" />
            </el-form-item>
          </el-col>
        </el-row>
      </div>

    </el-form>
  </div>
</template>

<script>
import api from '@/api'
import Sticky from '@/components/Sticky'
import Warn from './Warn'
import UploadImage from '@/components/Upload/UploadImage'
// import Tinymce from '@/components/Tinymce'
export default {
  name: 'NewsDetail',
  components: {
    Sticky,
    Warn,
    UploadImage,
    // Tinymce
  },
  props: {
    /**
     * 是否为编辑
     */
    isEdit: {
      type: Boolean,
      default: false
    }
  },
  data() {
    const nameValidate = (rule, value, callback) => {
      if (value === undefined || value.length <= 0) {
        callback(new Error('请输入名称'))
      } else {
        callback()
      }
    }
    const usernameValidate = (rule, value, callback) => {
      if (value === undefined || value.length <= 0) {
        callback(new Error('请输入用户名'))
      } else {
        callback()
      }
    }
    const sortValidate = (rule, value, callback) => {
      if (+value < -128 || +value > 127) {
        callback(new Error('排序值错误'))
      } else {
        callback()
      }
    }
    // const imageValidate = (rule, value, callback) => {
    //   if (value.length === 0) {
    //     callback(new Error('请上传图片'))
    //   } else {
    //     callback()
    //   }
    // }
    const discountValidate = (rule, value, callback) => {
      if (Number.isNaN(+value) || +value < -128 || +value > 127) {
        callback(new Error('让利设置错误'))
      } else {
        callback()
      }
    }
    return {
      id: -1,
      loading: false,
      postForm: {
        discount: 0,
        color: 'draft',
        status: true,
        sort: 0,
        image: [],
        address_id: null,
        // is_shop: 1
        is_shop: 0
      },
      rules: {
        username: [{ validator: usernameValidate, trigger: 'blur' }],
        discount: [{ validator: discountValidate, trigger: 'blur' }],
        name: [{ validator: nameValidate, trigger: 'blur' }],
        sort: [{ validator: sortValidate, trigger: 'change' }]
        // image: [{ validator: imageValidate, trigger: 'change' }]
      },
      // 分类
      categoryList: [],
      // 地区
      addressList: [],
      // 是否为线下店
      shopList: [
        {
          label: '是',
          value: 1
        },
        {
          label: '否',
          value: 0
        }
      ]
    }
  },
  created() {
    /**
     * 获取编辑数据
     */
    if (this.isEdit) {
      this.id = (this.$route.params && this.$route.params.id) || -1
      this.fetchData(this.id)
    }
    this.getCategory()
  },
  methods: {
    // 获取分类
    async getCategory() {
      const response = await api.supplier.getCategory()
      this.categoryList = response.data.list
      this.addressList = response.data.address
    },
    /**
     * 获取编辑数据
     */
    async fetchData(id) {
      const response = await api.supplier.view({ id })
      this.postForm = Object.assign({}, response.data)
      // 状态
      this.postForm.status = +this.postForm.status === 1
      this.postForm.is_shop = +this.postForm.is_shop
      // this.postForm.is_home = +this.postForm.is_home === 1
      // 图片
      if (this.postForm.image) {
        const image = this.postForm.image.map(x => x.image)
        const list = []
        image.forEach(x => {
          if (x) {
            list.push({
              id: +x.id,
              url: x.thumbnail_path
            })
          }
        })
        this.postForm.image = [...list]
      } else {
        this.postForm.image = []
      }
    },
    /**
     * 提交表单
     */
    submitForm() {
      this.$refs.postForm.validate(valid => {
        if (valid) {
          this.loading = true
          // 状态
          const status = this.postForm.status ? 1 : 0
          // const is_home = this.postForm.is_home ? 1 : 0
          // 图片
          let image = []
          if (this.postForm.image.length > 0) {
            image = this.postForm.image.map(x => x.id)
          }
          api.supplier.edit({
            id: this.id,
            ...this.postForm,
            status,
            // is_home,
            image,
          }).then(response => {
            this.loading = false
            this.$notify({
              title: '成功',
              message: response.message || '操作成功',
              type: 'success',
              duration: 2000
            })
            this.$router.push(`/supplier/edit/${response.data.id}`)
          }).finally(() => {
            this.loading = false
          })
        }
      })
    },
    /**
     * 图片上传
     */
    onSuccess(data, fileList) {
      if (data && data.id) {
        this.postForm.image.push({
          id: data.id,
          url: data.thumbnail
        })
      }
    },
    /**
     * 删除图片
     */
    onRemove(data, fileList) {
      if (data && data.id) {
        this.postForm.image = this.postForm.image.filter(x => x.id !== data.id)
      }
    }
  }
}
</script>

<style scoped lang="scss">
.detail-container {
  //
}
</style>
